package xupt.com.bolg.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import xupt.com.bolg.entity.Bolg;
import xupt.com.bolg.entity.User;
import xupt.com.bolg.service.impl.BolgServiceImpl;
import xupt.com.bolg.service.impl.UserServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class RegisterController {
    @Autowired
    BolgServiceImpl bolgService;
    @Autowired
    UserServiceImpl userService;
    @GetMapping("/register")
    public String skipRegister(){
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@RequestParam(value = "name")String name,@RequestParam(value = "code")String code,
                               @RequestParam("password")String password, @RequestParam("email")String email,
                               @RequestParam("phone")String phone, HttpServletRequest request, Model model){
       request.setAttribute("name",name);request.setAttribute("password",password);
       request.setAttribute("phone",phone);request.setAttribute("email",email);


        User user=new User(name,password);
       user.setPhone(phone);
       user.setEmail(email);
       String YZcode=(String)request.getSession().getAttribute("YZcode");
       if(!YZcode.equalsIgnoreCase(code)){
           request.setAttribute("msg","验证码错误");
           return "register";
       }
        if(userService.saveUser(user)){
            //注册成功直接登录
            request.getSession().setAttribute("name",name);
            List<Bolg> all = bolgService.findAll();
            System.out.println("bolg个数"+all.size());
            model.addAttribute("bolgs",all);
            return "redirect:/main.html";
        }else {
            request.setAttribute("msg","不对起该用户名已经注册！！");
            return "register";
        }
    }
}
